import axios from 'axios'
import store from './store'
import router from './router'

// 
// token放到请求header，传给后端


export default function setAxios(){
    // 请求拦截
    axios.interceptors.request.use(
        config=>{
            if(store.state.token)
            {
                config.headers.token = store.state.token
            }
            return config
        }
    )

    // 每次有返回，先过拦截器
    axios.interceptors.response.use(
        response=>{
            if(response.status == 200)
            {
                const data = response.data
                if(data.code == -1)
                {
                    // 过期，重新登录，清空vuex的token，localstorage的session
                    store.commit('settoken', '')
                    localStorage.removeItem('token')

                    // 跳转到login页面
                    router.replace({path:'/login'})
                }
                return data
            }
            return response
        }
    )
}
